# encoding: utf-8
# @File   : creator_frame.py
# @Author : 乖孩子
# @Date   : 2025/07/24 16:30:46

import tkinter as tk
from tkinter import ttk, messagebox, scrolledtext
import threading
import time
from ui.theme import Theme
from core.point_creator import PointCreator


class PointCreatorFrame(ttk.Frame):
    def __init__(self, parent, return_callback, logger, log_collector):
        super().__init__(parent, style="TFrame")
        self.parent = parent
        self.return_callback = return_callback
        self.logger = logger
        self.log_collector = log_collector
        self.point_creator = PointCreator(logger)

        # 创建UI
        self.create_widgets()

        self.logger.info("测点创建界面初始化完成")

    def create_widgets(self):
        """创建测点创建界面组件"""
        # 标题
        ttk.Label(
            self,
            text="测点创建工具",
            font=Theme.FONTS["subtitle"],
            foreground=Theme.COLORS["primary"]
        ).pack(pady=20)

        # 参数设置卡片
        param_card = ttk.Frame(self, style="Card.TFrame")
        param_card.pack(fill=tk.X, padx=100, pady=10)

        # 参数设置区域
        param_frame = ttk.Frame(param_card, style="TFrame")
        param_frame.pack(fill=tk.X, pady=10)

        # 起始测点编号
        ttk.Label(param_frame, text="起始测点编号:").grid(row=0, column=0, sticky=tk.W, padx=30, pady=10)
        self.start_point = tk.StringVar(value="0")
        ttk.Entry(param_frame, textvariable=self.start_point, width=10).grid(row=0, column=1, sticky=tk.W, pady=10)

        # 总测点数
        ttk.Label(param_frame, text="总测点数:").grid(row=0, column=2, sticky=tk.W, padx=30, pady=10)
        self.total_points = tk.StringVar(value="1000")
        ttk.Entry(param_frame, textvariable=self.total_points, width=10).grid(row=0, column=3, sticky=tk.W, pady=10)

        # 服务器IP
        ttk.Label(param_frame, text="服务器IP:").grid(row=0, column=4, sticky=tk.W, padx=30, pady=10)
        self.server_ip = tk.StringVar(value="192.168.1.111")
        ttk.Entry(param_frame, textvariable=self.server_ip, width=15).grid(row=0, column=5, sticky=tk.W, pady=10)

        # 按钮区域
        button_frame = ttk.Frame(param_card, style="TFrame")
        button_frame.pack(fill=tk.X, pady=15)

        self.start_button = ttk.Button(
            button_frame,
            text="开始创建",
            command=self.start_creation,
            style="Accent.TButton"
        )
        self.start_button.pack(side=tk.LEFT, padx=(50, 10))

        self.stop_button = ttk.Button(
            button_frame,
            text="停止",
            command=self.stop_creation,
            state=tk.DISABLED
        )
        self.stop_button.pack(side=tk.LEFT, padx=10)

        ttk.Button(
            button_frame,
            text="返回",
            command=self.return_callback
        ).pack(side=tk.RIGHT, padx=50)

        # 进度区域
        progress_card = ttk.Frame(self, style="Card.TFrame")
        progress_card.pack(fill=tk.BOTH, expand=True, padx=100, pady=10)

        # 进度条
        progress_frame = ttk.Frame(progress_card, style="TFrame")
        progress_frame.pack(fill=tk.X, pady=10)

        self.progress = ttk.Progressbar(progress_frame, orient=tk.HORIZONTAL, mode='determinate')
        self.progress.pack(fill=tk.X, pady=(0, 10))

        # 状态标签
        status_frame = ttk.Frame(progress_card, style="TFrame")
        status_frame.pack(fill=tk.X, pady=(0, 10))

        ttk.Label(status_frame, text="成功:").pack(side=tk.LEFT, padx=5)
        self.success_label = ttk.Label(status_frame, text="0", foreground=Theme.COLORS["success"])
        self.success_label.pack(side=tk.LEFT, padx=5)

        ttk.Label(status_frame, text="失败:").pack(side=tk.LEFT, padx=5)
        self.error_label = ttk.Label(status_frame, text="0", foreground=Theme.COLORS["danger"])
        self.error_label.pack(side=tk.LEFT, padx=5)

        ttk.Label(status_frame, text="进度:").pack(side=tk.LEFT, padx=5)
        self.progress_label = ttk.Label(status_frame, text="0/0")
        self.progress_label.pack(side=tk.LEFT, padx=5)

        # 日志区域
        log_frame = ttk.LabelFrame(progress_card, text="操作日志", style="TFrame")
        log_frame.pack(fill=tk.BOTH, expand=True, pady=10)

        self.log_text = scrolledtext.ScrolledText(
            log_frame,
            height=10,
            font=Theme.FONTS["mono"],
            wrap=tk.WORD,
            relief=tk.FLAT,
            bd=1
        )
        self.log_text.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)
        self.log_text.insert(tk.END, "等待创建操作...\n")
        self.log_text.config(state=tk.DISABLED)

        # 设置错误标签样式
        self.log_text.tag_config("error", foreground=Theme.COLORS["danger"])

    def log_message(self, message, is_error=False):
        """日志输出到界面和收集器"""
        self.log_text.config(state=tk.NORMAL)

        if is_error:
            self.log_text.insert(tk.END, message + "\n", "error")
            self.logger.error(message)
            self.log_collector.add_log(message, "ERROR")
        else:
            self.log_text.insert(tk.END, message + "\n")
            self.logger.info(message)
            self.log_collector.add_log(message)

        self.log_text.see(tk.END)
        self.log_text.config(state=tk.DISABLED)

    def update_progress(self, progress, success, error):
        """更新进度条和状态"""
        self.progress['value'] = progress
        total = success + error
        self.progress_label.config(text=f"{total}/{self.total}")
        self.success_label.config(text=str(success))
        self.error_label.config(text=str(error))

    def update_status(self, success, data):
        """更新最终状态"""
        if success:
            self.log_message(f"创建完成! 成功: {data['success']}, 失败: {data['error']}")
        else:
            self.log_message(f"创建失败: {data}", is_error=True)

        self.start_button.config(state=tk.NORMAL)
        self.stop_button.config(state=tk.DISABLED)

    def start_creation(self):
        """开始创建测点"""
        try:
            start = int(self.start_point.get())
            total = int(self.total_points.get())
            server_ip = self.server_ip.get()

            if not server_ip:
                self.log_message("请输入服务器IP地址", is_error=True)
                messagebox.showerror("错误", "请输入服务器IP地址")
                return

            if start < 0 or total <= 0:
                self.log_message("起始编号和总测点数必须是正整数", is_error=True)
                messagebox.showerror("错误", "起始编号和总测点数必须是正整数")
                return

            self.total = total
            self.running = True
            self.progress['value'] = 0
            self.success_label.config(text="0")
            self.error_label.config(text="0")
            self.progress_label.config(text="0/0")

            self.log_message("=" * 60)
            self.log_message(f"开始创建测点: 起始编号 {start}, 总数 {total}")
            self.log_message(f"目标服务器: {server_ip}")

            self.start_button.config(state=tk.DISABLED)
            self.stop_button.config(state=tk.NORMAL)

            # 启动创建线程
            threading.Thread(
                target=self.point_creator.create_points,
                args=(start, total, server_ip, self.update_progress, self.update_status),
                daemon=True
            ).start()

        except ValueError:
            self.log_message("请输入有效的数字", is_error=True)
            messagebox.showerror("错误", "请输入有效的数字")

    def stop_creation(self):
        """停止创建测点"""
        self.running = False
        self.point_creator.stop_creation()
        self.log_message("用户请求停止创建操作...")
        self.stop_button.config(state=tk.DISABLED)